// file: arc/X86/hardware/hardware/text.c
// autor: jiang xinpeng

#include <lib/type.h>
#include <arch/text.h>
#include <arch/cursor.h>
#include <arch/console.h>

uint8_t *textaddress = (uint8_t *)TEXT_BUFFER_ADDRESS;

void TextPutChar(uint8_t ch, uint8_t color)
{
    int x, y;
    uint16_t position;
    uint8_t *vbuffer = (uint8_t *)(page_enable ? (textaddress + PAGE_HIGH_BASE) : (textaddress));

#if CONSOLE_HAS_CURSOR
    // buffer point
    position = ReadCursor();
#endif
    vbuffer = vbuffer + (position * 2);

    // if is a printf char
    if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ((ch >= 32) && (ch <= 126)))
    {
        // write char to video buffer
        *(vbuffer + TEXT_CHAR_OFF) = ch;
        *(vbuffer + TEXT_COLOR_OFF) = color;
    }
}

void TextCleanScreen(uint8_t color)
{
    uint8_t *buffer = (uint8_t *)(page_enable ? (textaddress + PAGE_HIGH_BASE) : (textaddress));

    for (int i = 0; i < TEXT_CHARS_MAX; i++)
    {
        *(buffer + i + TEXT_CHAR_OFF) = 0x20;
        *(buffer + i + TEXT_COLOR_OFF) = color;
        // next char buffer
        buffer += 2;
    }
}

void TextCopy(int srcx, int srcy, int x, int y)
{
    uint8_t *buffer_src = (uint8_t *)(page_enable ? (textaddress + PAGE_HIGH_BASE) : (textaddress)) + (srcy * CHARS_PER_LINE + srcx) * 2, *buffer_targe = textaddress + (y * CHARS_PER_LINE + x) * 2;
    // copy char and color
    *(buffer_targe + TEXT_CHAR_OFF) = *(buffer_src + TEXT_COLOR_OFF);
    *(buffer_targe + TEXT_COLOR_OFF) = *(buffer_src + TEXT_COLOR_OFF);
}

// clean targe area
void TextClearArea(int x, int y, int size, int color)
{
    uint8_t *buffer = (uint8_t *)(page_enable ? (textaddress + PAGE_HIGH_BASE) : (textaddress)) + (y * CHARS_PER_LINE + x) * 2;

    // fill area
    for (int i = 0; i < size; i++)
    {
        *(buffer + TEXT_CHAR_OFF) = 0x20;
        *(buffer + TEXT_COLOR_OFF) = color;
        // next char buffer
        buffer += 2;
    }
}